package com.jc.gameconter.controller.h5game;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.Base64Util;
import com.jc.common.util.CryptoUtils;
import com.jc.ds.base.service.BaseService;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.GameUser;
import com.jc.ds.model.UserToken;
import com.jc.ds.model.UserVrtAddress;
import com.jc.framework.enums.AppServerApi;
import com.jc.framework.enums.Booleans;
import com.jc.framework.enums.LogType;
import com.jc.framework.util.PropertyPlaceholder;
import com.jc.framework.web.ResponseBaseModel;
import com.jc.framework.web.ResponseResultModel;
import com.jc.gameconter.controller.BaseController;
import com.jc.model.AppRespModel;
import com.jc.service.appinterface.AppInterfaceService;
import com.jc.service.chain.ChainResult;
import com.jc.service.gameinterface.GameInterfaceService;
import com.jc.service.gameuser.GameUserService;
import com.jc.service.h5game.H5GameService;
import com.jc.service.userorder.UserOrderService;
import com.jc.service.usertoken.UserTokenService;
import com.jc.service.uservrtaddress.UserVrtAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

@SuppressWarnings("all")
@Controller
@RequestMapping("h5Game")
public class H5GameController extends BaseController {

    @Autowired
    private H5GameService h5GameService;
    @Autowired
    private AppInterfaceService appInterfaceService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private GameUserService gameUserService;
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private GameInterfaceService gameInterfaceService;


    final String userEncrypt = (String)PropertyPlaceholder.getProperty("user.encrypt");
    final String currencyName = (String)PropertyPlaceholder.getProperty("transfer.currency.name");
    final String changeMinAmount = (String)PropertyPlaceholder.getProperty("change.min.amount");
    final String withdrawMinAmount = (String)PropertyPlaceholder.getProperty("withdraw.min.amount");
    final String companyUserId = (String)PropertyPlaceholder.getProperty("company.user.id");


    @RequestMapping(value = "/platformInitialization" , method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> platformInitialization(HttpServletRequest request){
        ResponseBaseModel responseBaseModel = new ResponseBaseModel();
        try {
            if (StringUtils.isEmpty(request.getParameter("token"))){
                throw new BaseServiceException("必传参数为空");
            }
            
            
            // 调用二号系统根据token获取用户信息
            //String url,Map<String,Object> body,LogType logType
            
            AppRespModel appRespModel = appInterfaceService.AppInterfaceHttp(AppServerApi.GET_USER_MSG.getName(),new HashMap<String, Object>(){{
                put("token",request.getParameter("token"));
            }}, LogType.APP_GET_USER);
            getLoger().error("二号系统服务返回初始化参数:   " + JSONObject.toJSONString(appRespModel));
            JSONObject data = appRespModel.getData();
            if(data == null){
                throw new BaseServiceException("服务器异常!");
            }
            if(data.get("returnCode") != null && "1".equals(data.get("returnCode").toString())) {
            	responseBaseModel.setCode(4000);
                responseBaseModel.setMessage("登录信息已经过期，请您重新登录！");
                return new ResponseEntity<>(responseBaseModel, HttpStatus.OK);
            }
            if (data.get("userVRTAddressList") == null || StringUtils.isEmpty(data.get("userVRTAddressList").toString())){
//                throw new BaseServiceException("您还没有钱包地址，请去【钱包】栏目新增钱包地址后进行充值。 点击【确定】跳转到个人中心");
                responseBaseModel.setCode(9999);
                responseBaseModel.setMessage("您还没有钱包地址，请去【钱包】栏目新增钱包地址后进行充值。 点击【确定】跳转到个人中心");
                return new ResponseEntity<>(responseBaseModel, HttpStatus.OK);
            }
            Map<String,Object> userMap = new HashMap<String, Object>(){{
                //头像. 姓名 用户id,昵称
                put("userId",data.getLong("userId"));
                put("userPic",data.getString("userHeadUrl"));
                put("userVrtAddress",data.get("userVRTAddressList"));
                put("userNickName",data.getString("userNickname"));
            }};
            if (userMap == null){
                responseBaseModel.setCode(400);
                responseBaseModel.setMessage("登录失效");
                return new ResponseEntity<>(responseBaseModel, HttpStatus.BAD_REQUEST);
            }
            Map<String, Object> returnMap = h5GameService.platformInitialization(userMap);
            returnMap.remove("userVrtAddress");
            return new ResponseEntity<>(new ResponseResultModel<Map<String, Object>>(returnMap),HttpStatus.OK);
        } catch (Exception e) {
            responseBaseModel.setCode(500);
            responseBaseModel.setMessage(e.getLocalizedMessage());
            this.getLoger().error("初始化游戏大厅失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(responseBaseModel, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    /**
     * 是否同意免责声明
     * */
    @RequestMapping(value = "/isAgree",method = RequestMethod.POST)
    public ResponseEntity<?> isAgree(HttpServletRequest request){
        try{
            String userId = request.getParameter("userId");
            if (StringUtils.isEmpty(userId)){
                throw new BaseServiceException("必传参数为空");
            }
            GameUser gameUser = gameUserService.queryGameUser(Long.valueOf(userId));
            if (gameUser == null){
                throw new BaseServiceException("当前用户不存在");
            }
            gameUserService.modify(new GameUser(){{
                setId(gameUser.getId());
                setIsAgree(Booleans.TRUE.getName());
            }},false);
            return new ResponseEntity<>(new ResponseResultModel<String>(""),HttpStatus.OK);
        }catch (Exception e){
            this.getLoger().error("免责声明同意失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getLocalizedMessage());
            }}, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Autowired
    private UserVrtAddressService userVrtAddressService;

    /**
     * 查询地址列表
     * **/
    @RequestMapping(value = "/queryVrtAddressList" , method = RequestMethod.POST)
    public ResponseEntity<?> queryVrtAddressList(HttpServletRequest request){
        try{
            String userId = request.getParameter("userId");
            if (StringUtils.isEmpty(userId)){
                throw new BaseServiceException("必传参数为空 userid");
            }
            List<UserVrtAddress> userVrtAddresses = userVrtAddressService.queryAll(new UserVrtAddress() {{
                setUserId(Long.valueOf(userId));
            }});
            return new ResponseEntity<>(new ResponseResultModel<List<UserVrtAddress>>(userVrtAddresses),HttpStatus.OK);
        }catch (Exception e){
            this.getLoger().error("查询Vrt地址列表失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getLocalizedMessage());
            }}, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 设置默认地址
     * **/
    @RequestMapping(value = "/setDefault" , method = RequestMethod.POST)
    public ResponseEntity setDefault(HttpServletRequest request){
        try{
            String userId = request.getParameter("userId");
            String addressId = request.getParameter("addressId");
            if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(addressId)){
                throw new BaseServiceException("必传参数为空");
            }
            List<UserVrtAddress> userVrtAddresses = userVrtAddressService.queryAll(new UserVrtAddress() {{
                setUserId(Long.valueOf(userId));
            }});
            for (UserVrtAddress userVrtAddress:userVrtAddresses) {
                if (userVrtAddress.getId().toString().equals(addressId)){
                    userVrtAddress.setSelected(Booleans.TRUE.getName());
                }else{
                    userVrtAddress.setSelected(Booleans.FALSE.getName());
                }
                userVrtAddressService.modify(userVrtAddress,false);
            }
            return new ResponseEntity<>(new ResponseResultModel<String>(""),HttpStatus.OK);
        }catch (Exception e){
            this.getLoger().error("设置默认地址失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getLocalizedMessage());
            }}, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }






    /**
     * 用户数据加密
     * */
    @RequestMapping(value = "/userEncryption" , method = RequestMethod.POST)
    public ResponseEntity<?> userEncryption(HttpServletRequest request){
        try{
            //获取用户信息
            String user = request.getParameter("user");
            if (StringUtils.isEmpty(user)){
                throw new BaseServiceException("必传参数为空");
            }
            //加密字符串
            String encrypt = Base64Util.encode(CryptoUtils.encrypt(user, userEncrypt));
            return new ResponseEntity<>(new ResponseResultModel<String>(encrypt),HttpStatus.OK);
        }catch (Exception e){
            this.getLoger().error("加密用户信息失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getLocalizedMessage());
            }}, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询VRT余额和转账费比例
     * */
//    @RequestMapping("/queryVrtBalanceAndTransferFee")
//    public ResponseEntity<?> queryVrtBalanceAndTransferFee(HttpServletRequest request){
//        String  userId = request.getParameter("userId");
//        try{
//            if (StringUtils.isEmpty(userId)){
//                throw new BaseServiceException("必传参数为空");
//            }
//            Map<String,Object> resultMap = new HashMap<>();
//            //查询VRT余额
//            ChainResult chainResult = userOrderService.queryBalance(Long.valueOf(userId), currencyName);
//            String return_code = chainResult.getReturn_code();
//            BigDecimal vrtBalance = new BigDecimal(0);
//            if("SUCCESS".equals(return_code)){
//                vrtBalance = new BigDecimal(chainResult.getBalance());
//            }else{
//                return new ResponseEntity<>(new ResponseBaseModel(){{
//                    setCode(500);
//                    setMessage(chainResult.getReturn_msg());
//                }}, HttpStatus.OK);
//            }
//            resultMap.put("vrtBalance",vrtBalance);
//            //转账费比例
//            resultMap.put("vrtTransferFee",vrtTransferFee);
//            return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(resultMap),HttpStatus.OK);
//        }catch (Exception e){
//            this.getLoger().error("查询用户VRT信息失败 {} , {}", e.getLocalizedMessage(),e);
//            return new ResponseEntity<>(new ResponseBaseModel(){{
//                setCode(500);
//                setMessage(e.getLocalizedMessage());
//            }}, HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//    }

    /**
     * 查询金币余额
     * */
    @RequestMapping(value = "/queryUserGold" , method = RequestMethod.POST)
    public ResponseEntity<?> queryUserGold(HttpServletRequest request){
        String  userId = request.getParameter("userId");
        try{
            if (StringUtils.isEmpty(userId)){
                throw new BaseServiceException("必传参数为空 userId");
            }
            Map<String,Object> resultMap = new HashMap<>();
            GameUser gameUser = gameUserService.queryGameUser(Long.valueOf(userId));
            if (gameUser == null){
                throw new BaseServiceException("用户不存在 userId = "+userId);
            }
            //查询金币余额
            Map<String, Object> gameBalance = gameInterfaceService.getGameBalance(gameUser.getUserId());
            if (gameBalance.get("success").toString().equals("1")){
                //积分
                resultMap.put("amount",gameBalance.get("amount"));
            }else{
                throw new BaseServiceException("用户金币查询失败");
            }
            return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(resultMap),HttpStatus.OK);
        }catch (Exception e){
            this.getLoger().error("查询用户金币失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getLocalizedMessage());
            }}, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



    /**
     * 充值
     * */
    @RequestMapping(value = "/recharge" , method = RequestMethod.POST)
    public ResponseEntity<?> recharge(HttpServletRequest request){
        //校验支付密码
        try{
            String payPassWord = request.getParameter("payPassWord");
            String money = request.getParameter("money");
            String userId = request.getParameter("userId");
            if (StringUtils.isEmpty(payPassWord) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(money)){
                throw new BaseServiceException("必传参数为空");
            }
            //判断充值的VRT数量是否是整数
            boolean integer = isInteger(money);
            if (!integer){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("充值VRT数量必须为整数");
                }},HttpStatus.OK);
            }
            String remarks = "无备注";
            if (StringUtils.isNotEmpty(request.getParameter("remarks"))){
                remarks = request.getParameter("remarks");
            }
            GameUser gameUser = gameUserService.queryGameUser(Long.valueOf(userId));
            if (gameUser == null){
                throw new BaseServiceException("当前用户不存在");
            }
            AppRespModel appRespModel = appInterfaceService.AppInterfaceHttp(AppServerApi.CHECK_PAY_PASSWORD.getName(), new HashMap<String, Object>() {{
                put("password", payPassWord);
                put("id",gameUser.getUserId());
            }}, LogType.APP_CHECK_PAYPASSWORD);
            if ("1".equals(appRespModel.getReturnCode())){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("支付密码不正确");
                }},HttpStatus.OK);
            }
            //单次是否小于最小充值金额
            BigDecimal bigMoney = new BigDecimal(money);
            BigDecimal bigMinAmount = new BigDecimal(changeMinAmount);
            if (bigMinAmount.compareTo(bigMoney) > 0){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("单次最小充值VRT数量不低于"+changeMinAmount+"。");
                }},HttpStatus.OK);
            }
            //调用充值接口
            ChainResult transfer = userOrderService.transfer(currencyName, bigMoney, gameUser.getUserId(), Long.valueOf(companyUserId),remarks , 0 , null,null);
            if ("SUCCESS".equals(transfer.getReturn_code())){
                //充值成功
                return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(new HashMap<String, Object>(){{
                    put("code",200);
                }}),HttpStatus.OK);
            }else if ("FAIL".equals(transfer.getReturn_code())){
                //充值失败
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage(transfer.getReturn_msg());
                }},HttpStatus.OK);
            }else{
                //充值失败
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("很抱歉，充值失败！");
                }},HttpStatus.OK);
            }
        }catch (Exception e){
            this.getLoger().error("用户充值失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getLocalizedMessage());
            }},HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 提现
     * */
    @RequestMapping(value = "/withdraw" , method = RequestMethod.POST)
    public ResponseEntity<?> withdraw(HttpServletRequest request){

        try{
            //拿到token和地址id
            String vrtToken = request.getParameter("vrtToken");
            String userId = request.getParameter("userId");
            String money = request.getParameter("money");
            if(StringUtils.isEmpty(vrtToken) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(money)){
                throw new BaseServiceException("缺少必传参数");
            }
            //判断提现的VRT数量是否是整数
            boolean integer = isInteger(money);
            if (!integer){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("提现VRT数量必须为整数");
                }},HttpStatus.OK);
            }
            BigDecimal bigMoney = new BigDecimal(money);
            GameUser gameUser = gameUserService.queryGameUser(Long.valueOf(userId));
            if (gameUser == null){
                throw new BaseServiceException("当前用户不存在");
            }
            //根据用户id和token去查询token是否有效和一致
            List<UserToken> userTokens = userTokenService.queryAll(new UserToken() {{
                setUserToken(vrtToken);
                setUserId(Long.valueOf(userId));
                setIsDelete(Booleans.FALSE.getName());
            }});
            if(userTokens.size()>1 || userTokens.size() < 1){
                this.getLoger().error("提现token失效 userId = "+userId);
                throw new BaseServiceException("提现token失效,请刷新页面");
            }
            Boolean isWithdrawalOfExcess = userOrderService.isWithdrawalOfExcess(Long.valueOf(userId),bigMoney);
            if (!isWithdrawalOfExcess){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("当日最大提现额度为10万,您当日已达到最大额度");
                }},HttpStatus.OK);
            }
            //最低提现额度
            BigDecimal bigMinAmount = new BigDecimal(withdrawMinAmount);
            if (bigMinAmount.compareTo(bigMoney) > 0){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("单次最小提现VRT数量不低于"+withdrawMinAmount+"。");
                }},HttpStatus.OK);
            }
            BigDecimal amount = new BigDecimal(0);
            //是否存在这么多金币
            Map<String, Object> gameBalance = gameInterfaceService.getGameBalance(gameUser.getUserId());
            if (gameBalance.get("success").toString().equals("1")){
                //积分
                amount =  new BigDecimal(String.valueOf(gameBalance.get("amount")));
            }else{
                throw new BaseServiceException("用户金币查询失败");
            }
            if (bigMoney.compareTo(amount) >0){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("提现金额大于当前余额");
                }},HttpStatus.OK);
            }
            //减去游戏中的金币\
            Map<String, Object> stringObjectMap = gameInterfaceService.rechargeOrWithdraw(gameUser.getUserId(), new BigDecimal(Integer.valueOf(money)*(-1)));
            if ("0".equals(stringObjectMap.get("success").toString())){
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("很抱歉，请求游戏服务端发生错误, 提现失败！");
                }},HttpStatus.OK);
            }
            String remarks = "无备注";
            if (StringUtils.isNotEmpty(request.getParameter("remarks"))){
                remarks = request.getParameter("remarks");
            }
            //调用提现接口
            ChainResult transfer = userOrderService.transfer(currencyName, bigMoney, Long.valueOf(companyUserId), gameUser.getUserId(), remarks, 1 ,null,null);
            if (transfer == null){
                //调用失败 . 返还金币
                gameInterfaceService.rechargeOrWithdraw(gameUser.getUserId(), new BigDecimal(money));
                throw new BaseServiceException("【提现失败】服务器异常,请联系客服!");
            }
            if ("SUCCESS".equals(transfer.getReturn_code())){
                //作废VRTtoken 重新生成
                userTokenService.modify(new UserToken(){{
                    setUserId(gameUser.getUserId());
                    setId(userTokens.get(0).getId());
                    setIsDelete(Booleans.TRUE.getName());
                }},false);
                String token = UUID.randomUUID().toString();
                UserToken userToken = new UserToken();
                userToken.setCreateTime(new Date());
                userToken.setIsDelete(Booleans.FALSE.getName());
                userToken.setUserId(gameUser.getUserId());
                userToken.setUserToken(token);
                userTokenService.add(userToken,false);
                //提现成功
                return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(new HashMap<String, Object>(){{
                    put("code",true);
                }}),HttpStatus.OK);
            }else if ("FAIL".equals(transfer.getReturn_code())){
                //调用失败 . 返还金币
                gameInterfaceService.rechargeOrWithdraw(gameUser.getUserId(), new BigDecimal(money));
                //提现失败
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage(transfer.getReturn_msg());
                }},HttpStatus.OK);
            }else{
                //调用失败 . 返还金币
            	getLoger().error("请求游戏 ------------------------------------------->  {},{}", gameUser.getUserId(), new BigDecimal(money) );
                gameInterfaceService.rechargeOrWithdraw(gameUser.getUserId(), new BigDecimal(money));
                //提现失败
                return new ResponseEntity<>(new ResponseBaseModel(){{
                    setCode(9999);
                    setMessage("很抱歉，提现失败！");
                }},HttpStatus.OK);
            }
        }catch (Exception e){
            this.getLoger().error("用户提现失败 {} , {}", e.getLocalizedMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(){{
                setCode(500);
                setMessage(e.getMessage());
            }},HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
//    @Autowired
//    private GameInterfaceService gameInterfaceService;
//    @RequestMapping(value = "/test",method = RequestMethod.POST)
//    public void test(HttpServletRequest request){
//        gameInterfaceService.rechargeOrWithdraw(1L,new BigDecimal(+4000));
//    }

}

